import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class TopicProducer {
	public static void main(String[] args) {
		// 创建连接工厂
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		produce(factory, "asm");
		produce(factory, "se");
	}

	public static void produce(ActiveMQConnectionFactory factory, String topic) {
		try {
			// 创建连接工厂
			factory.setTrustAllPackages(true); // 设置信任所有包
			// 创建连接
			Connection connection = factory.createConnection();
			// 启动连接
			connection.start();
			// 创建会话
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			// 创建主题
			Topic sessionTopic = session.createTopic(topic);
			// 创建消息生产者
			MessageProducer producer = session.createProducer(sessionTopic);
			// 创建消息
			ObjectMessage message = session.createObjectMessage();
			message.setObject(new MyMessage("Hello, " + topic + " topic!"));
			// 发送消息
			producer.send(message);
			System.out.println("Sent message: " + message.getObject());
			// 关闭连接
			connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}